<?php

class Gmapsprofile_Widget_PlaceProfileController extends Engine_Content_Widget_Abstract
{
  protected $_requireProfileType = true;	

  public function indexAction()
  {
    $pageSubject = Engine_Api::_()->core()->hasSubject() ? Engine_Api::_()->core()->getSubject() : null;
	if( !$pageSubject ) return $this->setNoRender();	
	$viewer = Engine_Api::_()->user()->getViewer();
	$user = $viewer;
	if ($pageSubject) {
	  $this->view->user = $user = $pageSubject;
	  $translate = Zend_Registry::get('Zend_Translate');
	  $userLanguage = $user->language;
      if( !Zend_Locale::isLocale($userLanguage) ||
          $userLanguage == 'auto' ||
          !in_array($userLanguage, $translate->getList()) ) {
        $userLanguage = $translate->getLocale();
      }	  
	  $this->view->userLanguage = isset($userLanguage) ? $userLanguage : 'en';
	}  
	
	if( !Engine_Api::_()->authorization()->isAllowed('gmapsprofile', null, 'viewmy') ) return $this->setNoRender();	
	
    // Get table info
    $table = Engine_Api::_()->getItemTable('user');
    $userTableName = $table->info('name');
    $select = $table->select()
      ->setIntegrityCheck(false)
      ->from($userTableName)		
	  ->join("engine4_user_online", "engine4_user_online.user_id = `{$userTableName}`.user_id", "engine4_user_online.user_id AS online")
      ->where("{$userTableName}.user_id = ?", $user->getIdentity());
	$rawData = $table->fetchAll($select);  
	$this->view->online = count($rawData);	  
	  	
	$info_user = $this->locations($user, $_fieldType = 'user');
	$this->view->location = $info_user['location'];
	$this->view->territories = $info_user['territories'];
	$this->view->gender = $info_user['gender'];
	$this->view->birthdate = $info_user['birthdate'];
	
    $settings = Engine_Api::_()->getApi('settings', 'core');

	$this->view->scale = isset($settings->gmapsprofile_scale_profile) ? $settings->gmapsprofile_scale_profile : 16;
	$this->view->map_type = isset($settings->gmapsprofile_type_map) ? $settings->gmapsprofile_type_map : 'ROADMAP';		
  }
  
  public function locations($subject, $_fieldType = 'user')
  {
	$user = $subject;
	$gender = '';
	$birthdate = '';
	$settings = Engine_Api::_()->getApi('settings', 'core');
    // Set data
    $mapData = Engine_Api::_()->getApi('core', 'fields')->getFieldsMaps($_fieldType);
    $metaData = Engine_Api::_()->getApi('core', 'fields')->getFieldsMeta($_fieldType);
    $optionsData = Engine_Api::_()->getApi('core', 'fields')->getFieldsOptions($_fieldType);
	$valueData = Engine_Api::_()->fields()->getFieldsValues($user);
	$profile_type = Engine_Api::_()->fields()->getFieldsSearch($user);
	
	if ($profile_type['profile_type'] == "")
	  return array('location' => '', 'gender' => '', 'birthdate' => '', 'territories' => '');

    // Get top level fields
    $topLevelMaps = $mapData->getRowsMatching(array('field_id' => 0, 'option_id' => 0));
    $topLevelFields = array();
    foreach( $topLevelMaps as $map ) {
      $field = $map->getChild();
      $topLevelFields[$field->field_id] = $field;
    } 
  
    // Do we require profile type?
    // No
    if( !$this->_requireProfileType ) {
      $this->topLevelOptionId = '0';
      $this->topLevelFieldId = '0';
    }
    // Yes
    else {
      // Get top level field
      // Only allow one top level field
      if( count($topLevelFields) > 1 ) {
        throw new Engine_Exception('Only one top level field is currently allowed');
      }
      $topLevelField = array_shift($topLevelFields);
      // Only allow the "profile_type" field to be a top level field (for now)
      if( $topLevelField->type !== 'profile_type' ) {
        throw new Engine_Exception('Only profile_type can be a top level field');
      }

      // Get top level options
      $topLevelOptions = array();
      foreach( $optionsData->getRowsMatching('field_id', $topLevelField->field_id) as $option ) {
        $topLevelOptions[$option->option_id] = $option->label;
      }
	  $this->view->topLevelOptions = $topLevelOptions;

      // Get selected option
	  
      $option_id = $profile_type->profile_type;
      if( empty($option_id) || empty($topLevelOptions[$option_id]) ) {
        $option_id = current(array_keys($topLevelOptions));
      }
      $topLevelOption = $optionsData->getRowMatching('option_id', $option_id);

      if( !$topLevelOption ) {
        throw new Engine_Exception('Missing option');
      }
      $this->view->topLevelOption = $topLevelOption;
      $this->view->topLevelOptionId = $topLevelOption->option_id;
	  $level = 'gmapsprofile_level_' . $option_id;	
	  $fields_address = isset($settings->$level) ? explode(';', $settings->$level) : '';
      // Get second level fields
      $secondLevelMaps = array();
      if( !empty($option_id) ) {
        $secondLevelMaps = $mapData->getRowsMatching('option_id', $option_id);
        if( !empty($secondLevelMaps) ) {
		  $prefix = '';
		  $location = '';
		  $territories_user = '';
          foreach( $secondLevelMaps as $map ) {
            $oField = $map->getChild();
			$locale = Zend_Registry::get('Zend_Translate')->getLocale();			
			$territories = Zend_Locale::getTranslationList('territory', $locale, 2);			
	  		if ($oField && $oField->display) {
			  if (!empty($settings->$level) && in_array($oField->field_id, $fields_address))	{
			      $geo_value = $valueData->getRowsMatching('field_id', $oField->field_id);
			      $Data='';
	              foreach ($geo_value as $val) {
                    $label = $optionsData                 
                                ->getRowMatching('option_id', $val->value);
                    $Data = $label
                            ? $label->label
                            : $val->value;
                  }
				  if( !empty($Data) && isset($territories[$Data]) ) {
					$location .= !empty($Data) ? $prefix . $Data : '';
					$territories_user .= !empty($territories[$Data]) ? $prefix . $territories[$Data] : '';
					if ( !empty($Data) ) $prefix = ', ';
				  }	
				  else {
			        $location .= !empty($Data) ? $prefix . $Data : '';
					$territories_user .= !empty($Data) ? $prefix . $Data : '';
					if ( !empty($Data) ) $prefix = ', ';
				  }		
			  }	
			  elseif (empty($settings->$level)) {
			    switch ($oField->type) {
				case 'location': 
			      $Data = $valueData->getRowMatching('field_id', $oField->field_id);
			      $location .= !empty($Data->value) ?  $prefix .$Data->value : '';
				  $territories_user .= !empty($Data->value) ? $prefix . $Data->value : '';
				  $prefix = ', ';
			      break;
				case 'city':
			      $Data = $valueData->getRowMatching('field_id', $oField->field_id);
			      $location .= !empty($Data->value) ?  $prefix .$Data->value : '';
				  $territories_user .= !empty($Data->value) ? $prefix . $Data->value : '';
				  $prefix = ', ';
			      break;
				case 'country':
			      $Data = $valueData->getRowMatching('field_id', $oField->field_id);
				  if( !empty($Data->value) && isset($territories[$Data->value]) ) {
					$location .= !empty($Data->value) ? $prefix . $Data->value : '';
					$territories_user .= !empty($territories[$Data->value]) ? $prefix . $territories[$Data->value] : '';
					if ( !empty($Data->value) ) $prefix = ', ';
				  }	
				  else {
			        $location .= !empty($Data->value) ? $prefix . $Data->value : '';
					$territories_user .= !empty($Data->value) ? $prefix . $Data->value : '';
					if ( !empty($Data->value) ) $prefix = ', ';
				  }
			      break;	
				case 'zip_code':
			      $Data = $valueData->getRowMatching('field_id', $oField->field_id);
			      $location .= !empty($Data->value) ?  $prefix .$Data->value : '';
				  $territories_user .= !empty($Data->value) ? $prefix . $Data->value : '';
				  $prefix = ', ';
			      break;				  		  
				} 
			  }
			  switch ($oField->type) {
				case 'gender': 
			      $Data = $valueData->getRowMatching('field_id', $oField->field_id);
			      $value = $optionsData->getRowMatching('option_id', is_object($Data) ? $Data->value : 0);
  			      $gender = !empty($value->label) ? $value->label : '';
			      break;
				case 'birthdate':
			      $Data = $valueData->getRowMatching('field_id', $oField->field_id);
				  $birthdate = !empty($Data->value) ? $Data->value : '';
				  if (!empty($birthdate)) {
    				$parts = @explode('-', $birthdate);

				    // Error if not filled out
				    if( count($parts) < 3 || count(array_filter($parts)) < 3 ) {
				      //$this->addError('Please fill in your birthday.');
				      $birthdate = '';
				    }
					else {
				      $value = mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]);

				      // Error if too low
				      $date = new Zend_Date($value);
				      $birthdate = (int)(- $date->sub(time())  / 365 / 86400) . Zend_Registry::get('Zend_Translate')->_(' y/o');
					}  
				  }
			      break;				  
			  }						  
       		}
          }
        }
      }
    } 

	return array('location' => $location, 'territories' => $territories_user, 'gender' => $gender, 'birthdate' => $birthdate);
  }    
}  